// 测试修复后的计算器逻辑
// 模拟ClientCalculatorFixed组件的计算逻辑

// 模拟后端响应
const mockCalculate = (prior, post, op) => {
  let result;
  switch (op) {
    case 0: result = prior + post; break;
    case 1: result = prior - post; break;
    case 2: result = prior * post; break;
    case 3: 
      if (post === 0) throw new Error("Division by zero");
      result = prior / post; 
      break;
    default: throw new Error("Invalid operation");
  }
  return { result };
};

// 修复后的计算器状态模拟
class FixedCalculatorState {
  constructor() {
    this.board = 0;
    this.op = null;
    this.isNegative = 0;
    this.isErr = false;
    this.justCalculated = false; // 新增：标记是否刚计算完
    this.needsNewNumber = false; // 新增：标记是否需要开始新数字
    this.opReq = {
      prior: null,
      post: null,
      op: null
    };
  }

  // 修复后的数字输入逻辑
  push(n) {
    if (this.isErr) {
      this.isErr = false;
    }
    
    // 处理清除和退格
    if (n === -1) { // 清除
      this.opReq = { prior: null, post: null, op: null };
      this.board = 0;
      this.op = null;
      this.justCalculated = false;
      this.needsNewNumber = false;
      this.isNegative = 0;
      return;
    }
    
    if (n === -2) { // 退格
      this.board = Math.floor(this.board / 10);
      if (this.board === 0 && this.isNegative === 1) {
        this.isNegative = 0;
      }
      this.justCalculated = false;
      return;
    }
    
    // 如果刚计算完且输入数字，重置状态开始新计算
    if (this.justCalculated && n >= 0 && n <= 9) {
      this.justCalculated = false;
      this.needsNewNumber = false;
      this.opReq = { prior: null, post: null, op: null };
      this.op = null;
      this.board = n;
      return;
    }
    
    // 如果需要新数字（刚按了运算符），开始新数字
    if (this.needsNewNumber && n >= 0 && n <= 9) {
      this.needsNewNumber = false;
      this.board = n;
      this.justCalculated = false;
      return;
    }
    
    // 大数限制
    if (this.board >= 99999999 && n >= 0 && n <= 9) {
      return;
    }
    
    // 数字输入逻辑
    if (n >= 0 && n <= 9) {
      if (this.board === 0) {
        this.board = n;
      } else {
        this.board = this.board * 10 + n;
      }
      this.justCalculated = false;
    }
  }

  // 修复后的运算符按下逻辑
  pressOp(pop) {
    if (pop === this.op) {
      console.debug("press same op");
      this.op = null;
      return;
    }
    
    // 如果之前有运算符且有完整的表达式，先计算
    if (this.opReq.prior !== null && this.opReq.op !== null && !this.justCalculated) {
      this.calc();
    }
    
    // 设置运算符
    this.opReq.prior = this.board * (this.isNegative === 1 ? -1 : 1);
    this.isNegative = 0;
    this.op = pop;
    this.opReq.op = pop;
    this.justCalculated = false;
    this.needsNewNumber = true; // 标记需要新数字
  }

  // 修复后的计算逻辑
  calc() {
    console.debug("calc called, opReq:", this.opReq);
    
    if (this.opReq.prior === null || this.opReq.op === null) {
      console.debug("Incomplete expression, skipping calculation");
      return;
    }
    
    if (this.opReq.post === null) {
      this.opReq.post = this.board * (this.isNegative === 1 ? -1 : 1);
      this.isNegative = 0;
    }
    
    console.debug("Calculating:", this.opReq);
    
    try {
      const res = mockCalculate(this.opReq.prior, this.opReq.post, this.opReq.op);
      console.debug("Calculation result:", res);
      
      if (res.result === null) {
        this.board = 0;
        this.justCalculated = true;
        return;
      }
      
      this.board = Math.abs(res.result);
      if (res.result < 0) {
        this.isNegative = 1;
      } else {
        this.isNegative = 0;
      }
      
      this.op = null;
      // 重要：将结果设为下次计算的prior，并重置post
      this.opReq.prior = res.result;
      this.opReq.post = null;
      this.opReq.op = null;
      this.justCalculated = true;
      
    } catch (error) {
      console.error("Calculation error:", error);
      this.isErr = true;
      this.board = 0;
      this.justCalculated = true;
    }
  }
}

// 单元测试
function runFixedTests() {
  console.log("🧪 开始修复后计算器单元测试");
  console.log("=" + "=".repeat(49));

  let testsPassed = 0;
  let totalTests = 0;

  function test(name, testFn) {
    totalTests++;
    try {
      testFn();
      console.log(`✅ ${name}`);
      testsPassed++;
    } catch (error) {
      console.log(`❌ ${name}: ${error.message}`);
    }
  }

  // 基础运算测试
  test("基础加法: 5 + 3 = 8", () => {
    const calc = new FixedCalculatorState();
    calc.push(5);
    calc.pressOp(0); // +
    calc.push(3);
    calc.calc();
    if (calc.board !== 8) throw new Error(`Expected 8, got ${calc.board}`);
  });

  test("基础减法: 10 - 4 = 6", () => {
    const calc = new FixedCalculatorState();
    calc.push(1); calc.push(0); // 10
    calc.pressOp(1); // -
    calc.push(4);
    calc.calc();
    if (calc.board !== 6) throw new Error(`Expected 6, got ${calc.board}`);
  });

  test("基础乘法: 6 × 7 = 42", () => {
    const calc = new FixedCalculatorState();
    calc.push(6);
    calc.pressOp(2); // ×
    calc.push(7);
    calc.calc();
    if (calc.board !== 42) throw new Error(`Expected 42, got ${calc.board}`);
  });

  test("基础除法: 20 ÷ 4 = 5", () => {
    const calc = new FixedCalculatorState();
    calc.push(2); calc.push(0); // 20
    calc.pressOp(3); // ÷
    calc.push(4);
    calc.calc();
    if (calc.board !== 5) throw new Error(`Expected 5, got ${calc.board}`);
  });

  // 连续运算测试（修复后应该通过）
  test("连续运算: 1 + 1 = 2, 然后 × 3 = 6", () => {
    const calc = new FixedCalculatorState();
    // 1 + 1 = 2
    calc.push(1);
    calc.pressOp(0); // +
    calc.push(1);
    calc.calc();
    console.log(`第一步结果: ${calc.board}, justCalculated: ${calc.justCalculated}, opReq.prior: ${calc.opReq.prior}`);
    
    // 然后 × 3
    calc.pressOp(2); // ×
    calc.push(3);
    calc.calc();
    console.log(`最终结果: ${calc.board}, opReq.prior: ${calc.opReq.prior}`);
    
    if (calc.board !== 6) throw new Error(`Expected 6, got ${calc.board}`);
  });

  test("复杂连续运算: 2 × 3 = 6, 然后 + 4 = 10", () => {
    const calc = new FixedCalculatorState();
    // 2 × 3 = 6
    calc.push(2);
    calc.pressOp(2); // ×
    calc.push(3);
    calc.calc();
    console.log(`第一步结果: ${calc.board}, justCalculated: ${calc.justCalculated}`);
    
    // 然后 + 4 = 10
    calc.pressOp(0); // +
    calc.push(4);
    calc.calc();
    console.log(`最终结果: ${calc.board}`);
    
    if (calc.board !== 10) throw new Error(`Expected 10, got ${calc.board}`);
  });

  test("三步连续运算: 5 + 5 = 10, × 2 = 20, ÷ 4 = 5", () => {
    const calc = new FixedCalculatorState();
    // 5 + 5 = 10
    calc.push(5);
    calc.pressOp(0); // +
    calc.push(5);
    calc.calc();
    console.log(`第一步结果: ${calc.board}`);
    
    // × 2 = 20
    calc.pressOp(2); // ×
    calc.push(2);
    calc.calc();
    console.log(`第二步结果: ${calc.board}`);
    
    // ÷ 4 = 5
    calc.pressOp(3); // ÷
    calc.push(4);
    calc.calc();
    console.log(`最终结果: ${calc.board}`);
    
    if (calc.board !== 5) throw new Error(`Expected 5, got ${calc.board}`);
  });

  // 错误处理测试
  test("除零错误处理", () => {
    const calc = new FixedCalculatorState();
    calc.push(5);
    calc.pressOp(3); // ÷
    calc.push(0);
    calc.calc();
    if (!calc.isErr) throw new Error("Expected error flag to be set");
  });

  // 清除功能测试
  test("清除功能", () => {
    const calc = new FixedCalculatorState();
    calc.push(1); calc.push(2); calc.push(3);
    calc.pressOp(0);
    calc.push(-1); // 清除
    if (calc.board !== 0 || calc.op !== null) {
      throw new Error("Clear function failed");
    }
  });

  console.log("=" + "=".repeat(49));
  console.log(`📊 修复后测试结果: ${testsPassed}/${totalTests} 通过`);
  
  if (testsPassed === totalTests) {
    console.log("\n🎉 所有测试通过！连续计算问题已修复。");
  } else {
    console.log("\n🔍 仍有问题需要解决");
  }
  
  return testsPassed === totalTests;
}

// 运行测试
runFixedTests();